<?php

namespace App\Http\Controllers\login;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
//验证码
use Gregwar\Captcha\CaptchaBuilder;
//==============================前台登录=================
class LoginController extends Controller
{
    //
    public function index()
    {
    	return view("home.login");
    }
    public function dologin(Request $request)
    {
    	//dd($request);
    	$name = $request->input("user");
    	// $pass = $request->input("pwd");
    	$ob = DB::table("user")->where("username",$name)->first();
        if(empty($name)){
            return back()->with("msg","请输入账号");
        }
    	if($ob){
    		if($request->input("pwd")==$ob->userpassword){
    			session(["homeuser"=>$ob]);
    			return redirect("home");
    		}else{
    			return back()->with("msg","登录失败：密码错误");
    		}
    	}else{
    		return back()->with("msg","登录失败：账号不存在");
    	}
    	
    }
    //验证码
    public function capch($tmp)
    {
        //生成验证码图片的Builder对象，配置相应属性
        $builder = new CaptchaBuilder;
        //可以设置图片宽高及字体
        $builder->build($width = 200, $height = 50, $font = null);
        //获取验证码的内容
        $phrase = $builder->getPhrase();

        //把内容存入session
        session()->flash('milkcaptcha', $phrase);
        //生成图片
        return response($builder->output())->header("content-type","image/jpeg");
    }
    public function outlogin()
    {
        session()->forget("homeuser");
        return redirect("/home");
    }
    public function sign()
    {
        return view("home.regiest");
    }
    public function create(Request $request)
    {
        //dd($request);
        $yz = session()->get("milkcaptcha");
        if($yz != $request->input("yz")){
            return back()->with("msg","验证码错误");
        }
        if(empty($request->username)){
            return back()->with("msg","账号不能为空");

        }
        $messages = [
            "required"=>":attribute是必须的",
        ];
        $this->validate($request,[
            "username"=>"required|unique:user",       
        ],$messages);
        if(empty($request->userpassword) || empty($request->ma)){
            return back()->with("msg","密码不能为空");
        }
        $mi = $request->input("userpassword");
        $ma = $request->input("ma");
        if($mi != $ma){
            return back()->with("msg","两次密码不一致");
        }

        // dd($request);
        $data = $request->only('username','userpassword');
        //dd($data);
        $m = DB::table('user')->insertGetId($data);
        if($m>0)
        {
              return redirect("home/login");
        }
        
    }
}
